<template>
  <view class="container">
    <my-navbar-top></my-navbar-top>
    <view class="detail-page">
      <view class="banner">
        <swiper
          class="swiper"
          circular
          :indicator-dots="indicatorDots"
          indicator-color="#fff"
          indicator-active-color="#C9A063"
          :autoplay="autoplay"
          :interval="interval"
          :duration="duration"
          @change="handleSwiperChange"
        >
          <swiper-item v-for="(item, index) in bannerList" :key="item.id">
            <view class="swiper-item">
              <image
                :src="item"
                mode="widthFix"
                lazy-load
                @click.stop="previewImage(index)"
              />
              <!-- 遮罩 -->
              <view class="mask"></view>
            </view>
          </swiper-item>
        </swiper>
        <image
          class="fangda"
          src="/static/images/fangda.png"
          mode="widthFix"
          @click.stop="previewImageCommon()"
        >
        </image>
      </view>
      <view class="detail-info">
        <view class="price">
          <view class="price-item price-item-1">
            <text>售价 ￥</text>
            <text class="price-num">{{ detail.price }}</text>
            <text>/{{ detail.is_mi == 1 ? '米' : '件' }}</text>
          </view>
          <view class="price-item">
            <!-- <text>已售 {{ detail.sale }} 米</text> -->
            <!-- <text class="line">|</text> -->
            <text
              >库存 {{ detail.stock }}
              {{ detail.is_mi == 1 ? '米' : '件' }}</text
            >
          </view>
        </view>
        <view class="operation">
          <view class="operation-item">
            <!-- <text>货号</text>
            <text class="code">{{ detail.GSPDCode }}</text> -->
          </view>
          <view class="opt">
            <view class="opt-item" @click="handleCollect">
              <image
                style="width: 30rpx"
                :src="
                  detail.is_collect === 1
                    ? '/static/images/collect-s.png'
                    : '/static/images/collect-gray.png'
                "
                mode="widthFix"
              />
              <text>收藏</text>
            </view>
            <button
              open-type="share"
              class="opt-item"
              style="background: none; padding: 0"
            >
              <image
                style="width: 27rpx"
                src="/static/images/share-gray.png"
                mode="widthFix"
              />
              <text>分享</text>
            </button>
          </view>
        </view>
      </view>
      <view class="detail-desc">
        <view class="title">商品描述</view>
        <view class="content">
          {{ detail.desc }}
        </view>
      </view>
      <view class="detail-desc">
        <view class="title">
          <view>商品参数</view>
          <!-- <view class="right" @click="openParameter">
            <view>
              <text v-for="(item, index) in parameterList" :key="item.label">
                {{ item.label
                }}{{ index < parameterList.length - 1 ? '、' : '' }}
              </text>
            </view>
            <view class="icon">{{ parameterType ? '-' : '+' }}</view>
          </view> -->
        </view>
        <view class="content">
          <view
            class="parameter"
            v-for="item in parameterList"
            :key="item.label"
            >{{ item.label }}：{{ item.value }}
          </view>
        </view>
      </view>
      <view class="detail-desc">
        <view class="title">
          <view>商品详情</view>
        </view>
        <view class="content">
          <rich-text :nodes="detail.detail">
            <!-- 使用 rich-text 显示商品详情 -->
            <!-- 注意：detail.content 必须是 HTML 字符串格式 -->
          </rich-text>
        </view>
      </view>
      <view class="detail-desc">
        <view class="title">退换货及发货规则</view>
        <view class="content">
          <rich-text :nodes="detail.return_product">
            <!-- 使用 rich-text 显示商品详情 -->
            <!-- 注意：detail.content 必须是 HTML 字符串格式 -->
          </rich-text>
        </view>
      </view>
    </view>
    <!-- 底部 -->
    <view class="detail-footer">
      <view class="icons">
        <view
          class="home"
          @click="goToUrl('/pages/home/index')"
          style="margin-right: 55rpx"
        >
          <image src="/static/tabbar/home.png" mode="widthFix" />
          <view>首页</view>
        </view>
        <view class="cart" @click="goToUrl('/pages/cart/index')">
          <image src="/static/tabbar/cart.png" mode="widthFix" />
          <view>购物车</view>
          <text class="dot">{{ cartCount }}</text>
        </view>
      </view>
      <view class="buy add-cart" @click="handleAddCart('cart')"
        >加入购物车</view
      >
      <view class="buy buy-now" @click="handleAddCart('buy')">立即购买</view>
    </view>

    <!-- 加入购物车  -->
    <uni-popup ref="addCarPopup" :safeArea="false">
      <view class="add-cart-popup">
        <view class="add-cart-popup-content">
          <!-- 关闭 -->
          <view class="close" @click="$refs.addCarPopup.close()">
            <image src="/static/images/x.png" mode="widthFix" />
          </view>
          <view class="header">
            <!-- 图片 -->
            <view class="image">
              <image :src="detail.cover" mode="widthFix" />
            </view>
            <!-- 名称 -->
            <view>
              <view class="price-item price-item-1">
                <text>售价 ￥</text>
                <text class="price-num">{{ detail.price }}</text>
                <text>/{{ detail.is_mi == 1 ? '米' : '件' }}</text>
              </view>
              <view class="price-item">
                <text
                  >库存 {{ detail.stock }}
                  {{ detail.is_mi == 1 ? '米' : '件' }}</text
                >
              </view>
            </view>
          </view>
          <!-- 操作  -->
          <view class="operation">
            <view class="operation-title">
              购买数量/{{ detail.is_mi == 1 ? '米' : '件' }}
            </view>
            <view class="opt">
              <!-- + - 输入框 -->
              <view @click="changeNum('sub')">-</view>
              <input
                class="input"
                :disabled="detail.is_shangxian == 1"
                :type="fixed === 1 ? 'digit' : 'number'"
                :inputmode="fixed === 1 ? 'decimal' : 'numeric'"
                v-model="buy_number"
                @input="inputValue"
              />
              <view @click="changeNum('add')">+</view>
            </view>
          </view>
        </view>
        <view class="add-cart-popup-footer">
          <button class="primary-button" @click="handleConfirmAddCart">
            确定
          </button>
        </view>
      </view>
    </uni-popup>
    <!-- 悬浮按钮 -->
    <float-icon></float-icon>
    <!-- 库存不足弹框 -->
    <stock-popup ref="stockPopup" @close="initBuyNumber"></stock-popup>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import floatIcon from '@/components/floatIcon.vue'
import stockPopup from '@/components/stockPopup.vue'
export default {
  name: '',
  components: {
    stockPopup,
    floatIcon,
  },
  data() {
    return {
      goodId: '', // 商品ID
      indicatorDots: true,
      autoplay: true,
      interval: 3000,
      duration: 500,
      buy_number: 1, // 购买数量
      bannerList: [],
      detail: {},
      fixed: 0, // 是否为小数
      buyType: 'buy', // 购买类型，默认 'buy'，可选 'cart'
      currentSwiperIndex: 0, // 当前swiper索引
      parameterType: false, // 商品参数展开状态
    }
  },
  computed: {
    ...mapState(['cartCount']),
    // 商品参数
    parameterList() {
      let key = [
        {
          label: '品牌',
          key: 'brand',
        },
        {
          label: '幅宽',
          key: 'width',
        },
        {
          label: '克重',
          key: 'weight_info',
        },
        {
          label: '支数',
          key: 'zhishu',
        },
        {
          label: '成分',
          key: 'component_info',
        },
        {
          label: '尺码',
          key: 'size',
        },
        {
          label: '花型',
          key: 'flower_pattern',
        },
        {
          label: '产地',
          key: 'origin',
        },
      ]
      let list = []
      key.forEach((item) => {
        if (this.detail[item.key]) {
          list.push({
            label: item.label,
            value: this.detail[item.key],
          })
        }
      })
      return list
    },
  },
  onLoad(e) {
    console.log(e)
    this.initData(e.id)
    this.goodId = e.id || ''
    // 更新购物车数量
    this.getCartCount()
  },

  mounted(e) {},
  methods: {
    handleSwiperChange(e) {
      this.currentSwiperIndex = e.detail.current
    },
    initBuyNumber() {
      this.$refs.addCarPopup.close()
      this.initData(this.goodId)
    },
    previewImageCommon() {
      uni.previewImage({
        urls: this.bannerList,
        current: this.currentSwiperIndex,
      })
    },
    previewImage(index) {
      uni.previewImage({
        urls: this.bannerList,
        current: index,
      })
    },
    openParameter() {
      this.parameterType = !this.parameterType
    },
    // 输入框输入事件
    inputValue(e) {
      let value = e.detail.value
      console.log(e.detail, this.fixed)
      this.$nextTick(() => {
        // 小数点只能出现一次
        if (this.fixed === 1) {
          this.buy_number = value.replace(/[^\d.]/g, '') // 移除非数字字符
          if (this.buy_number.split('.').length > 2) {
            this.buy_number =
              this.buy_number.split('.')[0] +
              '.' +
              this.buy_number.split('.')[1]
          }
          // 小数点后只能有1位
          if (
            this.buy_number.split('.')[1] &&
            this.buy_number.split('.')[1].length > 1
          ) {
            this.buy_number =
              this.buy_number.split('.')[0] +
              '.' +
              this.buy_number.split('.')[1].slice(0, 1)
          }
        } else {
          this.buy_number = value.replace(/[^\d]/g, '') // 移除非数字字符
        }
      })
    },
    initData(id) {
      this.$util.showLoading()
      console.log('initData')
      this.$api
        .getGoodDetail({
          id,
        })
        .then((res) => {
          console.log(res)
          let { images = [], is_jia_type = 1 } = res.data
          this.bannerList = images || []
          this.detail = res.data
          this.fixed = is_jia_type == 0.1 ? 1 : 0 // 判断是否为小数
          if (res.data.is_shangxian == 1) {
            this.buy_number = res.data.stock
          } else {
            this.buy_number = is_jia_type == 0.1 ? '1.0 ' : '1'
          }
        })
    },
    // 修改数量
    changeNum(type) {
      let item = this.detail
      if (item.is_shangxian == 1) {
        this.buy_number = item.stock
        return
      }
      if (item.stock == 0) {
        uni.showToast({
          title: '库存不足',
          icon: 'none',
        })
        return
      }

      let step = Number(item.is_jia_type) || 1,
        fixed = Number(item.is_jia_type) === 0.1 ? 1 : 0
      if (type == 'sub') {
        if (this.buy_number == (fixed === 1 ? 0.1 : 1)) {
          return
        }
        this.buy_number = (Number(this.buy_number) - step).toFixed(fixed)
      }
      if (type == 'add') {
        this.buy_number = (Number(this.buy_number) + step).toFixed(fixed)
      }
      console.log(this.buy_number)
    },

    handleConfirmAddCart() {
      if (!this.buy_number) {
        uni.showToast({
          title: '请输入购买数量',
          icon: 'none',
        })
        return
      }
      if (this.buyType === 'buy') {
        this.getOrderInfo()
        return
      }
      this.$api
        .addCar({
          product_id: this.detail.id,
          buy_number: this.buy_number,
        })
        .then((res) => {
          if (res.code === 0) {
            this.$refs.addCarPopup.close()
            console.log(res)
            uni.showToast({
              title: '添加成功',
              icon: 'success',
            })
            // 更新购物车数量
            this.getCartCount()
          } else if (res.code == -1) {
            this.$refs.stockPopup.openPopup()
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        })
    },
    // 先校验订单能否生成
    getOrderInfo() {
      let o = {
        product_id: this.detail.id || '',
        buy_number: this.buy_number || '',
      }
      this.$api.orderInfo(o).then((res) => {
        console.log(res)
        if (res.code == 0) {
          // 如果是立即购买，跳转到结算页面
          uni.navigateTo({
            url: `/pages/settlement/index?id=${this.detail.id}&num=${this.buy_number}`,
          })
          this.$refs.addCarPopup.close()
        } else if (res.code == -1) {
          this.$refs.stockPopup.openPopup()
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none',
          })
        }
      })
    },

    // 获取购物车数量
    getCartCount() {
      this.$api.getCarCount().then((res) => {
        console.log(res)
        if (res.code === 0) {
          this.$store.commit('setCartCount', res.data.count)
        }
      })
    },

    handleAddCart(type) {
      let telephone = uni.getStorageSync('userInfo').telephone || ''
      if (!telephone && type === 'buy') {
        uni.navigateTo({
          url: '/pages/user/login/index',
        })
        return
      }

      this.buyType = type // 设置购买类型
      if (this.detail.is_shangxian == 1) {
        this.buy_number = this.detail.stock
      } else {
        this.buy_number = this.fixed === 1 ? '1.0' : '1' // 重置购买数量
      }
      // 打开加入购物车弹窗
      this.$refs.addCarPopup.open('bottom')
    },
    handleCollect() {
      this.$api
        .collect({
          product_id: this.detail.id,
        })
        .then((res) => {
          console.log(res)
          this.detail.is_collect = this.detail.is_collect === 1 ? 0 : 1
        })
    },
    goToUrl(url) {
      uni.switchTab({
        url,
      })
    },
  },
  onShareAppMessage() {
    return {
      title: this.detail.name || '商品详情',
      path: `/pages/detail/index?id=${this.detail.id}`,
      imageUrl: this.detail.cover || '/static/images/share-d.jpg',
    }
  },
  onShareTimeline() {
  	
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
